package com.itmuch.cloud.study.service.impl;

import com.itmuch.cloud.study.entity.TransportDetail;
import com.itmuch.cloud.study.service.TransportDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Service
public class TransportDetailServiceImpl implements TransportDetailService{

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public List<TransportDetail> findDetailByTransportIdAndMaterialId(String transportId,String materialId) {
		StringBuffer sBuffer = new StringBuffer("select * from t_portdetail where transportId='"+transportId+"'");
		
		if(!materialId.equals("")){
			sBuffer.append(" and material= '"+materialId+"'");
		}
		sBuffer.append(" order by item ");
		List<TransportDetail> lists  = null;
		try {
			
			lists = jdbcTemplate.query(sBuffer.toString(),new RowMapper<TransportDetail>() {
				@Override
				public TransportDetail mapRow(ResultSet rs, int rowNum) throws SQLException {
					TransportDetail transportDetail = new TransportDetail();
					transportDetail.setSendDeliveryQty(rs.getString("sendDeliveryQty"));
					if(rs.getString("deliveryQty") == null){
						transportDetail.setDeliveryQty("0");
					}else{
						transportDetail.setDeliveryQty(String.valueOf(rs.getInt("deliveryQty")));
					}
					transportDetail.setId(rs.getString("id"));
					transportDetail.setItem(rs.getString("item"));
					transportDetail.setMaterial(rs.getString("material"));
					transportDetail.setDescription(rs.getString("description"));
					transportDetail.setOrderNo(rs.getString("orderNo"));
					transportDetail.setItem(rs.getString("item"));
					return transportDetail;
				}
			});
		} catch (Exception e) {
			return null;
		}
		
		return lists;
	}


    @Override
    public int deleteDetailByTransportId(String id) {
	    String sql = "delete FROM t_portdetail where transportId='"+id+"'";
	    int num = jdbcTemplate.update(sql);
        return num;
    }

    @Override
    public boolean findIsScanByDetailIds(List<String> ids) {
	    String idStr = "";
        for (String id:ids) {
            idStr = idStr+"'"+id+"',";
        }
        String sql = "select count(id) from t_material_portdetail where transportDetailId in ("+idStr.substring(0,idStr.length()-1)+")";
        int num = (int) jdbcTemplate.queryForObject(sql, Integer.class);

        if(num != 0){
            return  true;
        }

        return false;
    }


    @Override
	public boolean saveSendDeliveryQty(Set<String> ids,int f,int delNum) {
		// TODO Auto-generated method stub
		StringBuffer sBuffer = null;
		List<String> lists = new ArrayList<String>(ids);
        /**
         * 如果是f=1,说明是扫描操作，发货数量就加一；
         * 如果是f=0，说明是删除重扫操作，发货数量减一，delNum代表一次删除重扫的数量，barcode可以一次传入多个值。
         */
		
		if(f == 1){
			sBuffer = new StringBuffer("update t_portdetail set sendDeliveryQty = sendDeliveryQty + 1 where id = ? ");
		}else if(f == 0){
			sBuffer = new StringBuffer("update t_portdetail set sendDeliveryQty = sendDeliveryQty-"+delNum+"  where id = ?");
		}

		int[] i = jdbcTemplate.batchUpdate(sBuffer.toString(), new BatchPreparedStatementSetter() {
			  
			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				// TODO Auto-generated method stub
				ps.setString(1,lists.get(i));
			}
			
			@Override
			public int getBatchSize() {
				// TODO Auto-generated method stub
				return lists.size();
			}
		});
		
		if(i!= null && i.length != 0){
			return true;
		}
		return false;
	}

    @Override
    public boolean saveSendDeliveryQty(Set<String> ids, Map<String, String> delNum) {
        String sql = "update t_portdetail set sendDeliveryQty = sendDeliveryQty-? where id = ?  ";
        List<String> lists = new ArrayList<String>(ids);
        int[] i = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                // TODO Auto-generated method stub
                ps.setString(1,delNum.get(lists.get(i)));
                ps.setString(2,lists.get(i));
            }

            @Override
            public int getBatchSize() {
                // TODO Auto-generated method stub
                return lists.size();
            }
        });

        if(i!= null && i.length != 0){
            return true;
        }
        return false;
    }


    @Override
	public boolean saveSendDeliveryQty(Set<String> ids) {
		// TODO Auto-generated method stub
		
		String sql = "update t_portdetail set sendDeliveryQty = 0 where id = ?  ";
		List<String> lists = new ArrayList<String>(ids);
		int[] i = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
			  
			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				// TODO Auto-generated method stub
				ps.setString(1,lists.get(i));
			}
			
			@Override
			public int getBatchSize() {
				// TODO Auto-generated method stub
				return lists.size();
			}
		});
		
		if(i!= null && i.length != 0){
			return true;
		}
		return false;
	}



	//结单的时候调用此方法，更新结单后的状态
	@Override
	public boolean updateMaterialAndTransportDetailStatusById(List<String> ids,int code) {
		// TODO Auto-generated method stub

		String idStrs = "";
		for (String str : ids) {
			idStrs = idStrs +"'"+str+"',";
			
		}
		String sqlSelect = "select id,sta from t_material_portdetail where id in  ("+idStrs.substring(0, idStrs.length()-1)+")";
		
		List<Map<String,Object>> lists = jdbcTemplate.queryForList(sqlSelect);
		
		
		String sql = null;
        /**
         *   如果code=0,结单成功，不管表中的状态为何值，都更改状态为SEND
         */



		if(code == 0){
			sql = "update t_material_portdetail set sta='SEND',sendTime=NOW() where id in ("+idStrs.substring(0, idStrs.length()-1)+")";
			int update = jdbcTemplate.update(sql);
			if(update != 0){
				return true;
			}
		//code=500，并且表中的状态为新建状态，说明结单失败，更改状态为FAIL
		}else if(code == 500 && lists.get(0).get("sta").equals("NEW")){
			sql = "update t_material_portdetail set sta='FAIL',sendTime=NOW() where id in ("+idStrs.substring(0, idStrs.length()-1)+")";
			int update = jdbcTemplate.update(sql);
		//如果code=500，表中的状态为FAIL，不做任何操作

		}else if(code == 500 && lists.get(0).get("sta").equals("FAIL")){
			//return false;
		}
		
		return false;
		
	}



	@Override
	public boolean findOrderStatusByDelivery(String delivery) {
		
		String sql = "SELECT COUNT(tmp.id) as number FROM t_material_portdetail tmp LEFT JOIN t_material tm ON tmp.materialId = tm.id "+
					"LEFT JOIN t_portdetail tpd ON tmp.transportDetailId = tpd.id "+
					"LEFT JOIN t_port tp ON tp.id = tpd.transportId WHERE tp.delivery = '"+delivery+"' AND tmp.sta = 'SEND'";
		
		
		Map<String, Object> map = jdbcTemplate.queryForMap(sql);
		if((Long)map.get("number") == 0){
			return false;
		}
		return true;
	}
	
}
